<?php
class AppController extends Controller {
    
    public $language = null;
    public $cn = null;
    public $ac = null;
    public $view = null;
    public $id = null;
    
    public $components = array(
        'DebugKit.Toolbar',
        'Session',
        'Auth' => array(
            'loginRedirect'  => array('controller' => 'home', 'action' => 'index'),
            'logoutRedirect' => array('controller' => 'home', 'action' => 'index'),
            'loginAction'    => array('controller' => 'home', 'action' => 'login'),
            'authError'      => 'No esta autorizado, por favor ingrese primero.'
        )
    );
    
    public function isAuthorized($user) {
        if ($this->name === 'Pages') return true;
        if (isset($user['role']) && $user['role'] === 'ADMIN') {
            return true; //Admin can access every action
        }
        return false; // The rest don't
    }
    
    private function captureParams() {
        $this->cn = $this->params->params['controller'];
        $this->ac = $this->params->params['action'];
        if (array_key_exists('language', $this->params->params)) {
            $this->language = $this->params->params['language'];
        }
        if (array_key_exists('view', $this->params->params)) {
            $this->view = $this->params->params['view'];
        }
        if (array_key_exists('id', $this->params->params)) {
            $this->view = $this->params->params['id'];
        }
    }
    
    private function setLanguage() {
        if (!empty($this->language)) {
            $lang = $this->params->params['language'];
        } else {
            $lang = 'es';
        }
        if (!in_array($lang, Configure::read('Creativos.languages'))) {
            $this->Session->setFlash(__("Idioma '$lang' no disponible."));
            $this->redirect(array(
                'language' => Configure::read('Creativos.defaultLanguage'),
                'controller' => $this->cn,
                'action' => $this->ac,
                'view' => $this->view,
                'id' => $this->id
            ));
            exit(0);
        }
        Configure::write('Config.language', $lang);
    }
    
    private function setPageTitle() {
        $title = Configure::read('Creativos.pagetitles.'.$this->cn.'.'.$this->ac);
        $this->set('page_title', $title);
    }
    
    public function beforeFilter() {
        $this->captureParams();
        $this->setLanguage();
        $this->setPageTitle();
        $this->Auth->allow('display');
    }
}
?>